package com.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.entity.Document;
import com.entity.User;
import com.util.DBHelp;
import com.util.PageHelp;
import com.util.RowMapper;

public class DocumentDao {
	private DBHelp<Document> db=new DBHelp<Document>();

	public long getCount(){
		String sql="select count(id) from t_document";
		return (Long) db.executeQueryForFunction(sql);
	}

	public PageHelp<Document> findByPage(PageHelp<Document> page) {
		StringBuilder sql=new StringBuilder();
		sql.append("select dt.createtime,dt.docmessage,dt.docname,dt.id,dt.projectid,dt.userid,tu.username,tu.image ");
		sql.append("from t_document AS dt ");
		sql.append("left join t_user AS tu on tu.id=dt.userid ");
		sql.append("order by dt.createtime desc limit ?,?");
		List<Document> list= db.executeQueryForList(sql.toString(), new DocumentRowMapper(),page.getOffSet(),page.getPageSize());
		page.setResult(list);
		return page;
	}
	
	public void saveDoc(Document doc) {
		String sql="insert into t_document(createtime,docmessage,docname,id,userid,projectid) values (?,?,?,?,?,?)";
		db.executeSQL(sql, doc.getCreateTime(),doc.getDocmessage(),doc.getDocname(),doc.getId(),doc.getUserid(),doc.getProjectid());
	}

	public void delDoc(String id) {
		String sql="delete from t_document where id=?";
		db.executeSQL(sql, id);
	}

	public void update(Document doc) {
		String sql="update t_document set docname=?,docmessage=? where id=?";
		db.executeSQL(sql, doc.getDocname(),doc.getDocmessage(),doc.getId());
	}
	
	private class DocumentRowMapper implements RowMapper<Document>{
		public Document mapRow(ResultSet rs) throws SQLException {	
			Document d=new Document();
			d.setCreateTime(rs.getString("createtime"));
			d.setDocmessage(rs.getString("docmessage"));
			d.setDocname(rs.getString("docname"));
			d.setId(rs.getString("id"));
			d.setUserid(rs.getString("userid"));
			d.setProjectid(rs.getString("projectid"));
			
			User u=new User();
			u.setId(rs.getString("userid"));
			u.setImage(rs.getString("image"));
			u.setUserName(rs.getString("username"));
			d.setUser(u);
			return d;
			
		}	
	}

	public Document findById(String id) {
		// TODO Auto-generated method stub
		String sql="select dt.createtime,dt.docmessage,dt.docname,dt.id,dt.projectid,dt.userid,tu.username,tu.image from t_document AS dt left join t_user AS tu on tu.id=dt.userid where dt.id=?";
		return db.executeQueryForObject(sql, new DocumentRowMapper(), id);
	}
}
